//
//  MineCenterViewController.m
//  myCar
//
//  Created by 王子洁 on 14/11/9.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MineCenterViewController.h"
#import "MineViewController.h"
#import "CollectViewController.h"
#import "Base.h"
#import "ExaxtCar.h"
#import "ForumDetailController.h"
#import <ShareSDK/ShareSDK.h>
#import <SinaWeiboConnection/SSSinaWeiboUser.h>
#import "Friends.h"
#import "MyFriendsViewController.h"
#import "UIImageView+WebCache.h"
#import "AboutCarViewController.h"
#import "WebColor.h"
#import "HttpViewController.h"
#import "CollectionCell.h"
@interface MineCenterViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *forumCollection;
@property (nonatomic, retain) UICollectionView *carCollection;
@property (nonatomic, retain)UIImageView *myImageView;  //微博头像
@property (nonatomic, retain)UILabel *nameLabel;     // 微博名称
@property (nonatomic, retain) NSMutableArray *forumArr;
@property (nonatomic, retain) NSMutableArray *myCarArr;
@property (nonatomic, retain)NSMutableArray *friArr;

@end

@implementation MineCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.friArr = [NSMutableArray array];
       
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    
    
    self.view.backgroundColor = [WebColor whiteSmoke];
    self.navigationController.navigationBar.translucent = NO;
    
    CGFloat x = self.view.frame.size.width;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, x, 200)];
    
    [self.view addSubview:view];
    
    
    
    UIImageView *viewImage = [[UIImageView alloc] initWithFrame:view.frame];
    [viewImage setImage:[UIImage imageNamed:@"jianbian.jpg"]];
    [view addSubview:viewImage];
    [viewImage release];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]init];
    tap1.numberOfTapsRequired = 1;
    [tap1 addTarget:self action:@selector(loginWeibo)];
    [view addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]init];
    [view addGestureRecognizer:tap2];
    tap2.numberOfTapsRequired = 2;
    
    // 头像
    self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 80, 80)];
    [self.myImageView setImage:[UIImage imageNamed:@"geren.png"]];
    [view addSubview:self.myImageView];
    [_myImageView release];
    [tap2 addTarget:self action:@selector(cancelButtonClicked:)];
    
    
    
    
    
    
    // 微博名称
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 30, 130, 30)];
    self.nameLabel.text = @"请登录";
    [view addSubview:self.nameLabel];
    [_nameLabel release];
    
    // 好友
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(220, 90, 80, 35);
    button.backgroundColor = [UIColor clearColor];
    [button setTitle:@"微博好友" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(friendsClicked:) forControlEvents:UIControlEventTouchUpInside];
    button.tintColor = [UIColor whiteColor];
    button.layer.borderWidth = 1;
    button.layer.borderColor = [UIColor whiteColor].CGColor;
    [view addSubview:button];
    
    // 我的收藏
    UIButton *mySave = [UIButton buttonWithType:UIButtonTypeSystem];
    mySave.frame = CGRectMake(20, 140, 80, 50);
    [mySave addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    mySave.tintColor = [UIColor whiteColor];
    mySave.backgroundColor = [WebColor lightSkyBlue];
    [mySave setTitle:@"我的收藏" forState:UIControlStateNormal];
    [view addSubview:mySave];
    
    // 设置
    UIButton *setting = [UIButton buttonWithType:UIButtonTypeSystem];
    setting.frame = CGRectMake(120, 140, 80, 50);
    setting.backgroundColor = [WebColor lightSkyBlue];
    setting.tintColor = [UIColor whiteColor];
    [setting addTarget:self action:@selector(settingClicked:) forControlEvents:UIControlEventTouchUpInside];
    [setting setTitle:@"设置" forState:UIControlStateNormal];
    [view addSubview:setting];
    // 关于
    UIButton *about = [UIButton buttonWithType:UIButtonTypeSystem];
    about.frame = CGRectMake(220, 140, 80, 50);
    about.backgroundColor = [WebColor lightSkyBlue];
    about.tintColor = [UIColor whiteColor];
    [about addTarget:self action:@selector(aboutClicked:) forControlEvents:UIControlEventTouchUpInside];
    [about setTitle:@"关于" forState:UIControlStateNormal];
    [view addSubview:about];
    UILabel *history = [[UILabel alloc] initWithFrame:CGRectMake(10, 210, 100, 30)];
    history.backgroundColor = [UIColor clearColor];
    history.text = @"最近访问";
    history.textColor = [WebColor silver];
    history.textAlignment = 1;
    [self.view addSubview:history];
    [history release];
    UILabel *forum = [[UILabel alloc] initWithFrame:CGRectMake(10, 250, 30, 50)];
    forum.backgroundColor = [WebColor silver];
    forum.textColor = [WebColor white];
    forum.textAlignment = 1;
    forum.text = @"论坛";
    forum.font = [UIFont systemFontOfSize:17];
    forum.numberOfLines = 0;
    [self.view addSubview:forum];
    [forum release];
    UILabel *car = [[UILabel alloc] initWithFrame:CGRectMake(10, 310, 30, 50)];
    car.backgroundColor = [WebColor silver];
    car.text = @"车系";
    car.font = [UIFont systemFontOfSize:17];
    car.textColor = [WebColor white];
    car.textAlignment = 1;
    car.numberOfLines = 0;
    
    [self.view addSubview:car];
    
    
    [car release];
    [view release];
    [self createCollection];
}
- (void)viewWillAppear:(BOOL)animated
{
    //[self reversArr:[self localTokenWithFilePath:]];
    self.myCarArr = [NSMutableArray arrayWithArray:[self localTokenWithFilePath:@"seekCar.plist"]] ;
    [self.carCollection reloadData];
    self.forumArr = [NSMutableArray arrayWithArray:[self localTokenWithFilePath:@"myForum.plist"]] ;
    [self.forumCollection reloadData];
    
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:20],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    
   
    //
    
    
}
#pragma mark collection
- (void)createCollection
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(61, 40);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 10;
    // 整个section 的布局 距离边界的距离（上  左 下 右）
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.forumCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(35 , 250, self.view.bounds.size.width - 50, 40)collectionViewLayout:flowLayout];
    self.forumCollection.delegate = self;
    self.forumCollection.dataSource = self;
    self.forumCollection.backgroundColor = [UIColor clearColor];
    self.forumCollection.scrollEnabled = NO;
    [self.forumCollection registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"forum"];
    [self.view addSubview:self.forumCollection];
    
    
    
    
    UICollectionViewFlowLayout *flowLayout1 = [[UICollectionViewFlowLayout alloc]init];
    flowLayout1.itemSize = CGSizeMake(61, 40);
    flowLayout1.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout1.minimumInteritemSpacing = 5;
    flowLayout1.minimumLineSpacing = 10;
    // 整个section 的布局 距离边界的距离（上  左 下 右）
    flowLayout1.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);

    self.carCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(35 , 310, self.view.bounds.size.width - 50, 40) collectionViewLayout:flowLayout1];
    
    self.carCollection.delegate = self;
    self.carCollection.dataSource = self;
    self.carCollection.scrollEnabled = NO;
    self.carCollection.backgroundColor = [UIColor clearColor];
    [self.carCollection registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"car"];
    [self.view addSubview:self.carCollection];
    [flowLayout release];
    [flowLayout1 release];
    
}

#pragma mark collectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.forumCollection) {
        return self.forumArr.count;
       
    }
        return self.myCarArr.count;
   
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.forumCollection) {
        CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forum" forIndexPath:indexPath];
            Base *base = self.forumArr[self.forumArr.count - 1 - indexPath.row];
           cell.cellLabel.text = base.name;
        cell.cellLabel.font = [UIFont systemFontOfSize:14];
        
            return cell;
            
            
            
    }
        CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"car" forIndexPath:indexPath];
        ExaxtCar *car = self.myCarArr[self.myCarArr.count - 1 -   indexPath.row];
        cell.cellLabel.text = car.serialName;
        cell.cellLabel.font = [UIFont systemFontOfSize:14];
    
        return cell;
 
    
   
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.forumCollection) {
        Base *base = self.forumArr[self.forumArr.count - 1 - indexPath.item];
        ForumDetailController *forumDetailVC = [[ForumDetailController alloc]init];
        forumDetailVC.base = base;
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
        
    } else {
        ExaxtCar *car = self.myCarArr[self.myCarArr.count - 1 - indexPath.item];
        HttpViewController *httpVC = [[HttpViewController alloc]init];
        httpVC.car = car;
        [self.navigationController pushViewController:httpVC animated:YES];
        [httpVC release];
    }
}
- (NSArray *)localTokenWithFilePath:(NSString *)filePath
{
    NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *arrPath = [cachesPath stringByAppendingPathComponent:filePath];;
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:arrPath];
   
    return arr;
}

// 微博登录
- (void)loginWeibo
{
    
    if ([self.myImageView.image isEqual: [UIImage imageNamed:@"geren.png"]]) {
        [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
            if (result) {
                NSLog(@"新浪微博授权成功！");
                NSLog(@"uid:%@",[userInfo uid]);
                NSLog(@"nickname:%@",[userInfo nickname]);
                NSLog(@"profileImage:%@",[userInfo profileImage]);
                
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 390, 200, 50)];
                label.layer.cornerRadius = 6;
                label.backgroundColor = [UIColor lightGrayColor];
                [self.view addSubview:label];
                label.textAlignment = NSTextAlignmentCenter;
                label.text = @"登录成功" ;
                label.tag = 1000;
                [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(tempLabel) userInfo:nil repeats:YES];
                [label release];
                self.nameLabel.text = [userInfo nickname];
                [self.myImageView setImageWithURL:[NSURL URLWithString:[userInfo profileImage]]];
                [self getFiendsOfWeiBo];
            }else{
                NSLog(@"新浪微博授权失败");
                NSLog(@"错误码:%d,错误描述:%@",[error errorCode],[error errorDescription]);
            }
        }];
    } else {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(60, 390, 200, 40)];
        //label.backgroundColor = [UIColor cyanColor];
        label.text = @"点击两下就可以注销了";
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 1001;
        label.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:label];
        
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(tempLabel) userInfo:nil repeats:YES];
        [label release];
    }
    
}

- (void)tempLabel
{
    for (int i = 1000; i < 1002; i++) {
        UILabel *label = (UILabel *)[self.view viewWithTag:i];
        [label removeFromSuperview];
    }
    
}



// 注销登录
- (void)cancelButtonClicked:(UIButton *)button
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"不要离开我" message:nil delegate:self cancelButtonTitle:@"愉快玩耍" otherButtonTitles:@" 残忍拒绝", nil];
    [alertView show];
    [alertView release];
}

#pragma  mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
        [self.friArr removeAllObjects];
        UIAlertView* alverView = [[UIAlertView alloc]initWithTitle:nil message:@"注销成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alverView show];
        self.nameLabel.text = @"请登录";
        [self.myImageView setImage:[UIImage imageNamed:@"geren.png"]];
    }
}

- (void)getFiendsOfWeiBo
{
    //self.friArr = [NSMutableArray array];
    [ShareSDK getFriendsWithType:ShareTypeSinaWeibo page: nil authOptions:nil result:^(SSResponseState state, NSArray *users, long long curr, long long prev, long long next, BOOL hasNext, NSDictionary *extInfo, id<ICMErrorInfo> error) {
        if (state == SSResponseStateSuccess) {
            
            for (SSSinaWeiboUser *user in users) {
                Friends *friend = [[Friends alloc] init];
                friend.idNum = user.uid;
                friend.name = user.nickname;
                friend.proImage = user.profileImage;
                [self.friArr addObject:friend];
            }
        }
        
    }];
    
}
// 微博好友
- (void)friendsClicked:(UIButton *)button
{
    if ([self.myImageView.image isEqual: [UIImage imageNamed:@"geren.png"]]) {
        [self loginWeibo];
    }
    MyFriendsViewController *friVC = [[MyFriendsViewController alloc] init];
    friVC.friArr = self.friArr;
    [self.navigationController pushViewController:friVC animated:YES];
    [friVC release];
}



- (void)buttonClicked:(UIButton *)button
{
    CollectViewController *mineVC = [[CollectViewController alloc] init];
    [self.navigationController pushViewController:mineVC animated:YES];
    [mineVC release];
}

- (void)settingClicked:(UIButton *)button
{
    MineViewController *mineVC = [[MineViewController alloc] init];
    [self.navigationController pushViewController:mineVC animated:YES];
    [mineVC release];
}

- (void)aboutClicked:(UIButton *)button
{
    AboutCarViewController *about = [[AboutCarViewController alloc] init];
    [self.navigationController pushViewController:about animated:YES];
    [about release];
}




//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
//{
//    return 4;
//}



//- (void)viewDidDisappear:(BOOL)animated
//{
//    for (int i = 0; i < self.forumArr.count - 1; i++) {
//        UIButton *button = (UIButton *)[self.view viewWithTag:10000 + i];
//        [button removeFromSuperview];
//    }
//    for (int i = 0; i < self.myCarArr.count; i++) {
//        UIButton *button = (UIButton *)[self.view viewWithTag:i + 100];
//        [button removeFromSuperview];
//    }
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
